package com.dragon.utilslibrary.tools;

import android.text.TextUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 采用 AES128/CBC/Nopadding+Base64进行网络请求参数加密解密编码
 * 这里按照业务的要求，分账号系统与业务系统分别加解密
 */
public class AESUtils {

    /**
     * 账号系统相关参数加密
     */
    public static String TOKENAESCBCNoPaddingAddZero(String key, String iv, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(toByte(key), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();
        int plaintextLength = clear.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }
        byte[] plaintext = new byte[plaintextLength];
        for (int i = 0; i < plaintext.length; i++) {
            plaintext[i] = '\0';
        }
        System.arraycopy(clear, 0, plaintext, 0, clear.length);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(toByte(iv)));
        byte[] encrypted = cipher.doFinal(plaintext);
        return AESCode(Base64Utils.encode(encrypted));
    }

    /**
     * 账号系统相关反解密
     */
    public static String TOKENAESCBCNoPaddingDecrypt(String key, String iv, String encrypted) throws Exception {
        encrypted = AESEncode(encrypted);
        SecretKeySpec skeySpec = new SecretKeySpec(toByte(key), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(toByte(iv)));
        byte[] temp = Base64Utils.decode(encrypted);
        byte[] decrypted = cipher.doFinal(temp);
        String result = new String(decrypted, "utf-8").replace("\0", "").trim();
        return result;
    }

    /**
     * 业务系统相关参数加密
     */
    public static String AESCBCNoPaddingAddZero(String key, String iv, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(toByte(key), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();
        int plaintextLength = clear.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }
        byte[] plaintext = new byte[plaintextLength];
        for (int i = 0; i < plaintext.length; i++) {
            plaintext[i] = '\0';
        }
        System.arraycopy(clear, 0, plaintext, 0, clear.length);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(toByte(iv)));
        byte[] encrypted = cipher.doFinal(plaintext);
        return AESCode(Base64Utils.encode(encrypted));
    }

    /**
     * 业务系统相关参数反解密
     *
     * @param encrypted
     * @return
     * @throws Exception
     */
    public static String AESCBCNoPaddingDecrypt(String key, String iv, String encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(toByte(key), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(toByte(iv)));
        byte[] temp = Base64Utils.decode(encrypted);
        byte[] decrypted = cipher.doFinal(temp);
        String result = new String(decrypted, "utf-8").replace("\0", "").trim();
        return result;
    }

    public static String toHex(String txt) {
        return toHex(txt.getBytes());
    }

    public static String fromHex(String hex) {
        return new String(toByte(hex));
    }

    public static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
        return result;
    }

    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    public static void appendHex(StringBuffer sb, byte b) {
        final String HEX = "0123456789ABCDEF";
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

    /**
     * 转换字符
     *
     * @param aes
     * @return
     */
    public static String AESCode(String aes) {
        if (!TextUtils.isEmpty(aes)) {
            aes = aes.replace("+", "-").replace("/", "_");
            return aes;
        }
        return null;
    }

    /**
     * 转换字符
     *
     * @param aes
     * @return
     */
    public static String AESEncode(String aes) {
        if (!TextUtils.isEmpty(aes)) {
            aes = aes.replace("-", "+").replace("_", "/");
            return aes;
        }
        return null;
    }

}
